<?php

namespace Budget\BudgetBundle\Controller;

use Budget\BudgetBundle\Entity\Expense;
use Budget\BudgetBundle\Entity\PlannedExpense;
use Budget\BudgetBundle\Form\ExpenseType;
use Budget\BudgetBundle\Entity\Expenses;
use Budget\BudgetBundle\Entity\User;
use Budget\BudgetBundle\Form\ExpensesType;
use Budget\BudgetBundle\Form\PlannedExpenseType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Budget\BudgetBundle\Services\ExpenseService;
use Budget\BudgetBundle\Helper\DateHelper;
use Budget\BudgetBundle\Model\Charts\ChartExpenses;
use Budget\BudgetBundle\Entity\FamilyMonth;

class ExpensesController extends MainController
{
    public function newAction(Request $request)
    {
        $user     = $this->getUser();
        $expenses = new Expenses();
        $expense  = new Expense();
        $em       = $this->getEntityManager();

        $expenses->getExpenses()->add($expense);
        $form = $this->createForm(new ExpensesType($user->getFamily()), $expenses);

        $plannedExpense     = new PlannedExpense();
        $formExpensePlanned = $this->createForm(new PlannedExpenseType($user->getFamily()), $plannedExpense);

        $this->checkFamilyMonth();
        $response = array("isSuccess" => false);
        if ($request->getMethod() == "POST") {
            $form->bind($request);

            if ($form->isValid()) {
                $em = $this->getEntityManager();
                foreach ($expenses->getExpenses() as $expense) {
                    $expense->setUser($user);
                    $expense->setCreatedBy($user);
                    $em->persist($expense);
                }
                $em->flush();
                $response = array("isSuccess" => true);
            }
            return new JsonResponse($response);
        }

        $categoryRepo      = $em->getRepository('BudgetBudgetBundle:Category');
        $categoriesForGrid = $categoryRepo->getCategoriesForFamilyToJson($user->getFamily());
        $categoriesForTree = $categoryRepo->getCategoriesForFamilyToJsonTree($user->getFamily());
        //get expenses
        $expensesArr      = $this->get('budget_expense')->getExpensesForFamilyToArray($this->getUser()->getFamily());
        $expensesListData = $this->get('budget_expense')->formatExpensesAsInitialData($expensesArr);

        //get planned expenses
        $planedExpensesArr       = $em->getRepository('BudgetBudgetBundle:PlannedExpense')->getPlannedExpensesForFamilyByMonth($user->getFamily());
        $plannedExpensesListData = $this->get('budget_expense')->formatPlannedExpensesAsInitialData($planedExpensesArr);

        // statistics
        $familyMonth     = $em->getRepository('BudgetBudgetBundle:FamilyMonth')->findCurrentForFamily($user->getFamily());
        $monthStatistics = $this->get('statistic')->generateStatistics($familyMonth);
        $groupedExpenses = $this->get('budget_expense')->groupByMainCategory($expensesArr);

        return $this->render('BudgetBudgetBundle:Expense:new.html.twig', array(
            'form'                    => $form->createView(),
            'form_expense_planned'    => $formExpensePlanned->createView(),
            'categoriesForGrid'       => $categoriesForGrid,
            'expensesListData'        => $expensesListData,
            'plannedExpensesListData' => $plannedExpensesListData,
            'categoriesForTree'       => $categoriesForTree,
            'monthStatistics'         => $monthStatistics,
            'period'                  => $this->get('family_month')->getPeriodFinance($familyMonth),
            'amount'                  => $this->get('budget_expense')->countTotalAmount($expensesListData),
            'groupedExpenses'         => $groupedExpenses,
            'familyMonth'             => $familyMonth,
        ));
    }

    /**
     * Creates familyMonth
     */
    protected function checkFamilyMonth(\DateTime $requestedDate = null)
    {
        $date = new \DateTime();

        if (!is_null($requestedDate) && $requestedDate <= $date) {
            $date = $requestedDate;
        }

        $em          = $this->getEntityManager();
        $family      = $this->getUser()->getFamily();
        $familyMonth = $em->getRepository('BudgetBudgetBundle:FamilyMonth')
            ->findByDateForFamily($date, $family);

        if (is_null($familyMonth)) {
            $year           = $date->format('Y');
            $month          = $date->format('n');
            $newFamilyMonth = new FamilyMonth();
            $newFamilyMonth->setFamily($family);
            $newFamilyMonth->setMonth($month);
            $newFamilyMonth->setYear($year);
            $newFamilyMonth->setStart($family->getStartMonthDate($year, $month));
            $newFamilyMonth->setEnd($family->getEndMonthDate($year, $month));
            $newFamilyMonth->setDateCreated($date);
            $em->persist($newFamilyMonth);
            $em->flush();
        }
    }


    /**
     * Returns data to expenses jqGrid
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function getExpensesJsonAction(Request $request)
    {
        $page  = $request->query->get('page', 1);
        $limit = $request->query->get('rows', -1);
        $sidx  = $request->query->get('sidx', 'e.date');
        $sord  = $request->query->get('sord', 'desc');
        $em    = $this->getEntityManager();
        $user  = $this->getUser();
        $date  = $request->query->get('date');

        $dateObj       = DateHelper::createDateObj($date);
        $requestParams = $request->query->all();
        //var_dump($request->query->all()); exit;
        if (!isset($requestParams['date'])) {
            $requestParams['date'] = $dateObj->format(DateHelper::FORMAT_MONTH_YEAR);
        }
        $response     = new JsonResponse();
        $requestArray = array();
        foreach ($requestParams as $k => $v) {
            $requestArray[] = array('name' => $k, 'value' => $v);
        }

        $where = "";
        if ($request->query->get('_search') == 'true') {
            $where = $em->getRepository('BudgetBudgetBundle:Expense')->getQuerySearch($requestArray, $user);
        }

        $expenses     = $this->get('budget_expense')->getExpensesForFamilyToArray($this->getUser()->getFamily(), $page, $limit, $sidx, $sord, $where);
        $expensesJson = $this->get('budget_expense')->getFormatExpensesToJson($expenses);
        $familyMonth  = $em->getRepository('BudgetBudgetBundle:FamilyMonth')->findByDateForFamily($dateObj, $this->getUser()->getFamily());
        $statistics   = $this->get('statistic')->generateStatistics($familyMonth);

        $groupedExpenses = $this->get('budget_expense')->groupByMainCategory($expenses);
        $data            = array(
            'familyMonthId'       => is_null($familyMonth) ? null : $familyMonth->getId(),
            'period'              => $this->get('family_month')->getPeriodFinance($familyMonth),
            'amount'              => $this->get('budget_expense')->countTotalAmount($expenses),
            'groupedExpensesHtml' => $this->get('twig')->render('BudgetBudgetBundle:Expense:_grouped_expenses.html.twig', array('groupedExpenses' => $groupedExpenses))
        );

        $response->setData(array_merge($expensesJson, $statistics, $data));

        return $response;
    }

//    public function getTotalSumAction(Request $request) 
//    {
//        $user         = $this->getUser();
//        $em           = $this->getEntityManager();
//        $categories   = $request->request->get('categories');
//        $dateTo       = $request->request->get('date_to');
//        $dateFrom     = $request->request->get('date_from');
//        $idCategories = array();
//        $response     = new \stdClass;
//
//        $categoryArray = explode(',', $categories);
//        if (count($categoryArray) > 0) {
//            $categoriesResult = $em->getRepository('BudgetBudgetBundle:Category')->findIdCategoriesForFamily($user->getFamily(), $categories);
//            if (count($categoriesResult) > 0) {
//                for ($j=0; $j<count($categoriesResult); $j++) {
//                    $idCategories[] = $categoriesResult[$j]['id'];
//                }
//            }
//        }
//        
//        $total = $this->get('budget_expense')->getTotalSumExpensesForFamily($user->getFamily(), $dateTo, $dateFrom, $idCategories);
//        if ($total['total']) {
//            $response->total = $total['total'];
//        } else {
//            $response->total = 0.00;
//        }
//        return new JsonResponse($response);
//    }

    public function dataToChartAction(Request $request)
    {
        $user       = $this->getUser();
        $em         = $this->getEntityManager();
        $categories = $request->query->get('categories');
        $dateTo     = $request->query->get('date_to');
        $dateFrom   = $request->query->get('date_from');
        $where      = $whereParameters = array();

        $dateToDB          = DateHelper::convertToYearMonth($dateTo);
        $dateFromDB        = DateHelper::convertToYearMonth($dateFrom);
        $where[]           = "e.date_created <= :dateTo";
        $where[]           = "e.date_created >= :dateFrom";
        $whereParameters[] = array('name' => ':dateTo', 'val' => $dateToDB . '-31 00:00:00');
        $whereParameters[] = array('name' => ':dateFrom', 'val' => $dateFromDB . '-01 24:59:59');

        $categoryArray = explode(',', $categories);
        if (count($categoryArray) > 0) {
            $categoriesResult = $em->getRepository('BudgetBudgetBundle:Category')->findIdCategoriesForFamily($user->getFamily(), $categories);
            if (count($categoriesResult) > 0) {
                $idCategories = array();
                for ($j = 0; $j < count($categoriesResult); $j++) {
                    $idCategories[] = $categoriesResult[$j]['id'];
                }
                if (count($idCategories) > 0) {
                    $where[]           = "e.category IN (:categories)";
                    $whereParameters[] = array('name' => ':categories', 'val' => array_values($idCategories));
                }
            }
        }

        //$chart = new ChartExpenses($em);
        //$expenses = $chart->getDataForFamilyToArray($user->getFamily(), null, null, 'e.date_created', null, array('where' => $where, 'parameters' => $whereParameters));
        //$expensesJson = $chart->getToDataJson($expenses, $dateToDB, $dateFromDB);

        //$expenses      =  $this->get('budget_expense')->getExpensesForFamilyToArray($this->getUser()->getFamily(), null, null, 'e.date_created', null, array('where' => $where, 'parameters' => $whereParameters));
        //$expensesJson  =  $this->get('budget_expense')->getFormatExpensesToChartJson($expenses, $dateToDB, $dateFromDB); 

        $expensesJson = $this->get('chart')->getExpensesToJson($user, $dateToDB, $dateFromDB, $where, $whereParameters);

        $response = new JsonResponse();
        $response->setData($expensesJson);
        return $response;
    }

    public function chartsAction()
    {
        return $this->render('BudgetBudgetBundle:expense:charts.html.twig');
    }

    public function getTotalBalanceAction(Request $request)
    {
        $dateTo            = $request->request->get('date_to');
        $dateFrom          = $request->request->get('date_from');
        $categories        = $request->request->get('categories');
        $em                = $this->getEntityManager();
        $categoriesArray   = explode(',', $categories);
        $response          = new \stdClass;
        $response->expense = 0;
        $response->income  = 0;


        //$income = $this->get('budget_income')->getTotalSumIncomesForFamily($this->getUser()->getFamily(), $dateTo, $dateFrom);
        //$expense = $this->get('budget_expense')->getTotalSumExpensesForFamily($this->getUser()->getFamily(), $dateTo, $dateFrom, $categoriesArray);           
        $income  = $em->getRepository('BudgetBudgetBundle:Income')->getTotalSumIncomesForFamilyQuery($this->getUser()->getFamily(), DateHelper::convertToYearMonth($dateTo) . '-01', DateHelper::convertToYearMonth($dateFrom) . '-31');
        $expense = $em->getRepository('BudgetBudgetBundle:Expense')->getTotalSumExpensesForFamilyQuery($this->getUser()->getFamily(), DateHelper::convertToYearMonth($dateTo) . '-01', DateHelper::convertToYearMonth($dateFrom) . '-31', $categoriesArray);

        if ($expense[0]['total']) {
            $response->expense = $expense[0]['total'];
        }
        if ($income[0]['total']) {
            $response->income = $income[0]['total'];
        }
        return new JsonResponse($response);
    }
}